from decimal import Decimal
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from goods.models import SKU
from orders.serializers import OredrSerializers, SaveOrderSerializer


# Create your views here.
class OrdersView(APIView):
    '''
        获取订单商品信息
    '''

    # def get_queryset(self):   可以使用ListAPIView 重写get_queryset
    def get(self, request):
        '''手写业务逻辑'''
        # 获取当前用户
        user = request.user
        # 建立redis连接
        conn = get_redis_connection('cart')
        # 获取选中状态的sku_id和count
        sku_id_count = conn.hgetall('cart_%s' % user.id)        #{ 16:1, 15:1 }
        sku_ids = conn.smembers('cart_selected_%s' % user.id)   #{15}
        #合并数据
        cart = {}           # {15:1}
        for sku_id in sku_ids:
            cart[int(sku_id)] = int(sku_id_count[sku_id])
        # 查询选中状态的商品对象
        skus = SKU.objects.filter(id__in = cart.keys())
        for sku in skus:
            sku.count = cart[sku.id]
        # 序列化返回
        #运费
        freight = Decimal(10)
        serializer = OredrSerializers({'freight':freight, 'skus':skus})

        return Response(serializer.data)


class SaveOrderView(CreateAPIView):
    """
    保存订单
    """
    permission_classes = [IsAuthenticated]
    serializer_class = SaveOrderSerializer
